package com.ppc.handler;

import com.ppc.constant.MessageConstant;
import com.ppc.exception.BaseException;
import com.ppc.result.Result;
import java.sql.SQLIntegrityConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 *
 * @author jianKangS1
 * @date 2023/12/20
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

  /**
   * @param ex
   * @return {@link Result }
   * @description
   */
  @ExceptionHandler
  public Result exceptionHandler(BaseException ex) {
    log.error("异常信息：{}", ex.getMessage());
    return Result.error(ex.getMessage());
  }

  /**
   * @param ex
   * @return {@link Result }
   * @description
   */
  @ExceptionHandler
  public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
    String message = ex.getMessage();
    if (message.contains("Duplicate entry")) {
      String[] splits = message.split(" ");
      String username = splits[2];
      String msg = username + MessageConstant.ALREADY_EXISTS;
      return Result.error(msg);
    } else {
      return Result.error(MessageConstant.UNKNOWN_ERROR);
    }
  }
}
